// -----------------------------------------------------------------------------
//
//  Author : 	Duke Zhou
//  Data : 		2016/7/28
//
// -----------------------------------------------------------------------------
//
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.IO;
using FibMatrix;

namespace Jelly.Editor.AssetBundle
{
	/// <summary>
	/// 表示AssetNode及其在构建时需要的额外信息
	/// </summary>
    internal class EditorAssetNode :AssetNode
    {
        public EditorAssetNode()
        {
            this.url = "";
            this.md5 = "";
        }
        public UnityEngine.Object asset;
        public string assetGUID;
        public bool dynamic;		// 只动态下载，不随包发布的资源
        public bool needExportBundle = true;	// 音视频不需要以bundle形式存在
        public string extension = AssetConfig.ASSETBUNDLE_EXT_NAME;
	    public List<EditorAssetNode> dependence;
	    public string finalExportName;
	    public int index;
	    public string referenceId;
        
        public override string ToString()
        {
            StringBuilder sb = new StringBuilder(200);
            string shortId = Path.GetFileName(id);
            int count = dependence != null ? dependence.Count : 0;
            //        if(count == 0)
            //        {
            //            sb.AppendFormat("\"{0}\"\n", shortId);
            //        }
            //        else
            //        {
            for (int i = 0; i < count; ++i)
            {
                AssetNode child = dependence [i];
                string dependenceShorId = Path.GetFileName(child.id);
                sb.AppendFormat("\"{0}\" -> \"{1}\";\n", shortId, dependenceShorId);
            }
            //        }
            return sb.ToString();
        }

		public static AssetConfig CreateAssetConfigFrom(string version, Dictionary<string, EditorAssetNode> assetMap)
		{
			AssetConfig config = new AssetConfig();
			config.version = version;
			AssetList al = config.resList = new AssetList();
			al.nodes = new AssetNode[assetMap.Count];

			Dictionary<string, EditorAssetNode>.Enumerator iter = assetMap.GetEnumerator();
			int index = 0;
			while (iter.MoveNext())
			{
				iter.Current.Value.index = index;
				al.nodes[index++] = iter.Current.Value;
				if (iter.Current.Value.dependence != null)
				{
					foreach (var depIter in iter.Current.Value.dependence)
					{
						depIter.otherDepend = true;
					}
				}
			}

			foreach (var node in al.nodes)
			{
				List<EditorAssetNode> deps = (node as EditorAssetNode).dependence;
				if (deps != null && deps.Count > 0)
				{
					node.dependIndexes = new int[deps.Count];
					for (int i = 0; i < deps.Count; ++i)
					{
						node.dependIndexes[i] = deps[i].index;
					}
				}
			}

			return config;
		}
	}
}